package com.caisejingyu.whales.common.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Base64;

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密工具
 *
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public class EncryptUtil {

    /** Base64加密 */
    @SuppressLint("GetInstance")
    public static String base64Encrypt(String rawStr) {
        if (!TextUtils.isEmpty(rawStr)) {
            try {
                // 密钥
                String salt = "xpos1qazZSE$xpos";
                Key aesKey = new SecretKeySpec(salt.getBytes(), "AES");
                Cipher cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.ENCRYPT_MODE, aesKey);
                byte[] encrypted = cipher.doFinal(rawStr.getBytes());
                return Base64.encodeToString(encrypted, Base64.NO_WRAP);
            } catch (Exception e) {
                throw new RuntimeException("Error happened when encrypting String = " + rawStr + " due to " + e.getMessage());
            }
        } else {
            throw new RuntimeException("Original String to be encrypted is null");
        }
    }

    /** MD5加密 */
    public static String encryptMD5(String value) {
        if (TextUtils.isEmpty(value)) {
            throw new NullPointerException("Original String to be encrypted is null");
        }
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(value.getBytes());
            byte[] bytes = md5.digest();// 加密
            StringBuilder hexValue = new StringBuilder();
            for (byte b : bytes) {
                int tmp = ((int) b) & 0xff;
                if (tmp < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(tmp));
            }
            return hexValue.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}
